<?php
class AuthorizeComponent extends Object
{
    /**
     * @var AppController
     */
    protected $controller;

    /**
     *
     * @var AuthComponent
     */
    protected $Auth;


    protected $groups;
    /**
     *
     * @param AppController $controller
     * @param array $setting
     */
    public function initialize(AppController $controller, $setting = array())
    {
        $this->controller = $controller;
        $this->Auth = $this->controller->Auth;
        $uid = $this->Auth->user('id');
        $this->groups = $this->controller->User->getGroups($uid);
    }

    public function isAuthorized()
    {
        if($this->Auth->user('id') == 1){
            return true;
        }
        
        return $this->controller->_access(
            $this->_getAccessType(),
            $this->controller->params);
    }

    public function check($perm, $groups = null)
    {
//        if ($this->controller->name == 'Users' && $this->controller->action == 'login') {
//            return true;
//        }

        if(count($this->groups)==0) {
            $uid = $this->Auth->user('id');
            $this->groups = $this->controller->User->getGroups($uid);
        }

        if(!is_array($groups)){
            $groups = $this->groups;
        }
        foreach($groups as $group){
            $perms = preg_split('/,/',$group['perm'], -1, PREG_SPLIT_NO_EMPTY);
            if (array_key_exists($perm, array_flip($perms))) {
                return true;
            }
        }
        
        return false;
    }

    protected function _getAccessType()
    {
        $this->Auth->mapActions($this->controller->actionMap);
        $method = ($this->Auth->action(':action'));
        //$accesType: hozzáférés tipusa
        $accessType = $this->Auth->actionMap[$method];
        if(!is_array($accessType)){
            $accessType = array($accessType);
        }
        return $accessType;
    }
}
?>
